#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include "ReaderWriterSolver.h"
#include "buffer.h"

#define SHM_KEY 1234

int main() {
    // 创建共享内存
    int shmid = shmget(SHM_KEY, sizeof(Buffer), IPC_CREAT | 0666);
    if (shmid == -1) {
        perror("shmget");
        return 1;
    }

    // 连接共享内存
    Buffer *buffer = (Buffer *)shmat(shmid, NULL, 0);
    if (buffer == (void *)-1) {
        perror("shmat");
        return 1;
    }

    // 初始化缓冲区
    initBuffer(buffer);

    MutexRWUnit_W rwUnit;
    if (!initMutexRWUnit_W(&rwUnit)) {
        perror("Failed to initialize mutex");
        return 1;
    }

    const char *messages[] = {"Hello", "World", "This", "is", "a", "test"};
    int numMessages = sizeof(messages) / sizeof(messages[0]);

    for (int i = 0; i < numMessages; i++) {
        mutexWrite_W(&rwUnit, "Producer", (void (*)(void *))(
            [](void *args) {
                Buffer *buf = (Buffer *)args;
                if (buf->count < BUFFER_SIZE) {
                    strcpy(buf->strings[buf->in], messages[i]);
                    buf->in = (buf->in + 1) % BUFFER_SIZE;
                    buf->count++;
                }
            }
        ), buffer);
        sleep(1);
    }

    // 分离共享内存
    shmdt(buffer);

    destroyMutexRWUnit_W(&rwUnit);
    return 0;
}